package com.zboot.zbootadmin.project.system.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.zboot.zbootadmin.common.annotation.Log;
import com.zboot.zbootadmin.common.constant.HttpStatus;
import com.zboot.zbootadmin.common.domain.ResponseData;
import com.zboot.zbootadmin.common.security.LoginUser;
import com.zboot.zbootadmin.common.security.service.TokenService;
import com.zboot.zbootadmin.common.utils.DateUtils;
import com.zboot.zbootadmin.common.utils.ExcelUtils;
import com.zboot.zbootadmin.common.utils.ServletUtils;
import com.zboot.zbootadmin.project.system.menu.entity.SysRoleMenu;
import com.zboot.zbootadmin.project.system.role.entity.SysRole;
import com.zboot.zbootadmin.project.system.role.entity.SysUserRole;
import com.zboot.zbootadmin.project.system.role.entity.vo.RoleVo;
import com.zboot.zbootadmin.project.system.role.service.SysRoleService;
import com.zboot.zbootadmin.project.system.role.service.SysUserRoleService;
import com.zboot.zbootadmin.project.system.user.domain.SysUser;
import com.zboot.zbootadmin.project.system.user.domain.dto.EditUserInfoDto;
import com.zboot.zbootadmin.project.system.user.domain.dto.SearchDto;
import com.zboot.zbootadmin.project.system.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author zyt
 * @since 2020-07-18
 */
@RestController
@RequestMapping("/sysUser")
@Slf4j
public class SysUserController {

    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;

    /**
     *
     * @Description: 此处将列表和条件查询整合到一起
     *
     * @auther: zyt
     * @date: 14:42 2020/3/22
     * @param: [searchDto]
     * @return: com.zboot.zbootstarter.project.entity.ResponseData
     *
     */
    @Log("用户列表")
    @PreAuthorize("@zboot.hasPermi('system:user:list')")
    @PostMapping("/getUserList")
    public ResponseData getUserList(@RequestBody SearchDto searchDto) {
        return new ResponseData(HttpStatus.SUCCESS,userService.getUserList(searchDto));
    }

    /**
     *
     * @Description: 新增用户
     *
     * @auther: zyt
     * @date: 15:29 2020/3/22
     * @param: [sysUser]
     * @return: com.zboot.zbootstarter.project.entity.ResponseData
     *
     */
    @Log("新增用户")
    @PreAuthorize("@zboot.hasPermi('sys:user:add')")
    @PostMapping("/saveUser")
    public ResponseData saveUser(@RequestBody SysUser sysUser) {
        userService.saveUser(sysUser);
        return new ResponseData(HttpStatus.SUCCESS,"新增成功");

    }

    /**
     *
     * @Description: 删除用户包括批量删除
     *
     * @auther: zyt
     * @date: 15:34 2020/3/22
     * @param: [sysUser]
     * @return: com.zboot.zbootstarter.project.entity.ResponseData
     *
     */
    @Log("删除用户")
    @PreAuthorize("@zboot.hasPermi('sys:user:delete')")
    @DeleteMapping("/deleteUser")
    public ResponseData deleteUser( @RequestBody String[] ids) {
        userService.deleteUser(ids);
        return new ResponseData(HttpStatus.SUCCESS,"删除成功");

    }

    /**
     *
     * @Description: 导出excel模板
     *
     * @auther: zyt
     * @date: 20:37 2020/3/31
     * @param: [response]
     * @return: void
     *
     */
    @Log("导出模板")
    @PreAuthorize("@zboot.hasPermi('sys:user:export')")
    @PostMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response) throws IOException {
        ExcelUtils<SysUser> excelUtils = new ExcelUtils<>();
        String [] titles = {"用户账号","用户昵称","邮箱",
                "电话","用户性别（0男 1女 2未知）","备注"};
        SXSSFWorkbook sxssfWorkbook = excelUtils.getTemplateWorkBook(titles,"用户模板");
         excelUtils.exportTemplate(response,sxssfWorkbook);
    }
    /**
     *
     * @Description: 导入用户信息
     *
     * @auther: zyt
     * @date: 21:52 2020/4/1
     * @param: [response]
     * @return: void
     *
     */
    @Log("导入用户")
    @PreAuthorize("@zboot.hasPermi('sys:user:import')")
    @PostMapping("/importUser")
    public ResponseData importUser( @RequestParam("file") MultipartFile uploadFile) throws IOException {
        return new ResponseData(HttpStatus.SUCCESS,"导入成功",userService.saveBatch(userService.ExportUserList(uploadFile)));
    }

    @Log("导出用户")
    @PreAuthorize("@zboot.hasPermi('sys:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response) {
        String name="用户导出信息";
        String [] titles = {"用户账号","用户昵称","邮箱",
                "电话","用户性别（0男 1女 2未知）","备注"};
        List<SysUser> userList = userService.list();
        ExcelUtils<SysUser> excelUtils = new ExcelUtils<>();
        String [] properties = {"userName","nickName","email","phonenumber","sex","remark"};
        excelUtils.downExcel(titles,userList,response,SysUser.class,properties);

    }

    @Log("编辑用户")
    @PreAuthorize("@zboot.hasPermi('sys:user:edit')")
    @GetMapping("/getEditUser/{userId}")
    public ResponseData getEditUser(@PathVariable String userId) {

        SysUser sysUser = userService.getEditUser(userId);
       return new ResponseData(HttpStatus.SUCCESS,sysUser);

    }

    @PutMapping("/edit")
    public ResponseData edit( @RequestBody SysUser sysUser) {
        userService.edit(sysUser);
        return new ResponseData(HttpStatus.SUCCESS,"修改成功");
    }


    @GetMapping("/getAllRoleList")
    public ResponseData getAllRoleList()
    {
       List<RoleVo> roleVos = userService.getAllRoles();
        return new ResponseData(HttpStatus.SUCCESS,roleVos);
    }

    @GetMapping("/getProfile")
    public ResponseData getProfile() {
        SysUser user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        SysUser sysUser = userService.getEditUser(user.getUserId().toString());
        return new ResponseData(HttpStatus.SUCCESS,sysUser);
    }

    @PutMapping("/profile")
    public ResponseData updateUserProfile( @RequestBody SysUser sysUser) {
        SysUser user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        sysUser.setUserId(user.getUserId());
        userService.edit(sysUser);
        return new ResponseData(HttpStatus.SUCCESS,"修改成功");
    }

    @PutMapping("/resetPwd")
    public ResponseData resetPwd( @RequestParam("newPassword") String newPassword) {
        userService.resetPwd(newPassword);
        return new ResponseData(HttpStatus.SUCCESS,"修改成功");
    }

    @PostMapping("/avatar")
    public ResponseData avatar(@RequestParam("avatarFile") MultipartFile avatarFile, HttpServletRequest request){
        String picUrl = userService.uploadPicture(request,avatarFile);
        return new ResponseData(HttpStatus.SUCCESS,"",picUrl);
    }
}

